package yl.hs.bmipfull.controllers.laboratory;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yl.hs.bmipfull.controllers.ControllerBase;
import yl.hs.bmipfull.pojo.laboratory.ProductInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.SaleContractProductsEntity;
import yl.hs.bmipfull.service.laboratory.IProductCateService;
import yl.hs.bmipfull.service.laboratory.IProductInfoService;
import yl.hs.bmipfull.service.salemanage.ISaleContractProductsService;
import yl.hs.bmipfull.service.system.ISearchViewService;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.viewmodels.OptionModel;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.SubmitModel;
import yl.hs.bmipfull.viewmodels.WebResult;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作用:  产品类别表控制层<br/>
 * 创建时间: 2021年05月24日 10时11分57秒 <br/>
 *
 * @author 谢东
 */
@Api(value = "产品类别表Web接口", tags = "实验室管理——产品类别表操作")
@RequestMapping(value = "/api/product/cate")
@RestController
public class ProductCateController extends ControllerBase {

    @Autowired
    IProductCateService service;

    @Autowired
    IProductInfoService productInfoService;

    @Autowired
    ISearchViewService svSVC;
    @Autowired
    ISaleContractProductsService saleContractProductsService;
    @ApiOperation(value = "查询产品类别表", notes = "查询产品类别表")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public WebResult queryList() {
        try {
            List<OptionModel> model = new ArrayList<>();
            var result = service.findList();
            result.forEach(t -> {
                model.add(new OptionModel(t.getSn(), t.getCateName(), null, t));
            });
            return success("查询成功", model);
        } catch (Exception e) {
            return error(e);
        }
    }

    @ApiOperation(value = "查询产品类别表", notes = "查询产品类别表")
    @RequestMapping(value = {"/option","/option/{sn}"}, method = RequestMethod.GET)
    public WebResult findList(@PathVariable(required = false) String sn) {
        try {
            List<OptionModel> model = new ArrayList<>();
            var result = service.findList();
            var products = productInfoService.queryAll();
            if(sn!=null){
               var ss = saleContractProductsService.queryBySaleBSn(sn).stream().map(SaleContractProductsEntity::getProductSN).collect(Collectors.toSet());
               var cate = saleContractProductsService.queryBySaleBSn(sn).stream().map(SaleContractProductsEntity::getProductCate).collect(Collectors.toSet());
               result =result.stream().filter(d->cate.contains(d.getSn())).toList();
               products =products.stream().filter(d->ss.contains(d.getSn())).toList();
            }
            List<ProductInfoEntity> finalProducts = products;
            result.forEach(t -> {
                List<ProductInfoEntity> productInfo = finalProducts.stream().filter(f -> f.getProductCateSN().equals(t.getSn())).collect(Collectors.toList());
                List<OptionModel> productModel = new ArrayList<>();
                productInfo.forEach(f -> {
                    var label = f.getProductName();
                    if (!Tl.isEmpty(f.getProductSpec())) {
                        label = String.format("%s[%s]", f.getProductName(), f.getProductSpec());
                    }
                    productModel.add(new OptionModel(f.getSn(), label, f));
                });
                model.add(new OptionModel(t.getSn(), t.getCateName(), productModel, t));
            });
            return success("查询成功", model);
        } catch (Exception e) {
            return error(e);
        }
    }

    @ApiOperation(value = "查询产品类别表", notes = "分页查询产品类别表")
    @RequestMapping(value = "/{rowNum}/{page}", method = RequestMethod.POST)
    public WebResult queryPage(@RequestBody PageQuery query,
                               @ApiParam(value = "页码") @PathVariable int page,
                               @ApiParam(value = "每页条数") @PathVariable int rowNum) {
        try {
            var result = service.queryPage(query, rowNum, page);
            svSVC.updateUserMenuView(query);
            return success("ok", result);
        } catch (Exception ee) {
            return error(ee);
        }
    }


    @ApiOperation(value = "查询产品类别表", notes = "根据产品类别表编号查询产品类别表")
    @RequestMapping(value = "/{sn}", method = RequestMethod.GET)
    public WebResult findBySn(@ApiParam(value = "编号") @PathVariable String sn) {
        return success("查询成功", service.findBySn(sn));
    }


    @ApiOperation(value = "保存产品类别表", notes = "查询/更新产品类别表信息")
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public WebResult saveMenu(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        Integer result;
        try {
            result = service.saveProductCate(submitModel.getData(), submitModel.getSn());
            if (result > 0) {
                return success("保存成功");
            } else if (result == -1) {
                return  fail("名称重复");
            } else {
                return fail("数据未保存");
            }
        } catch (Exception e) {
            return error(e);
        }
    }

    @ApiOperation(value = "删除产品类别表信息", notes = "根据产品类别表编号删除系产品类别表信息")
    @RequestMapping(path = "", method = RequestMethod.DELETE)
    public WebResult delete(@ApiParam(value = "产品类别表编号", name = "sn", allowMultiple = true, required = true) @RequestParam("sn") String[] sn) {
        var result=service.delete(sn);
        if ( result> 0) {
            return success("删除成功!");
        } else if (result==-1){
            return fail("删除失败,类别下具有产品信息的无法删除！");
        }else{
            return fail("删除失败");
        }

    }

    @ApiOperation(value = "根据产品编号修改状态", notes = "根据产品编号修改发货单状态")
    @RequestMapping(value = "changeStateBySn/{sn}/{state}", method = RequestMethod.GET)
    @ResponseBody
    public WebResult changeStateBySn(@PathVariable String sn, @PathVariable short state) {
        try {
            Integer result = service.changeStateBySn(sn.split(","), state);
            if (result > 0) {
                return success("数据已修改");
            }
            return fail("数据修改失败！");
        } catch (Exception ee) {
            return error(ee);
        }
    }
    @ApiOperation(value = "根据产品名称查询原材种类", notes = "根据产品名称查询原材种类")
    @RequestMapping(value = "/chackName", method = RequestMethod.GET)
    public WebResult chackName(@ApiParam(value = "产品名称") @RequestParam(name = "cateName") String cateName,@ApiParam(value = "产品名称编号") @RequestParam(name = "sn",required = false) String sn) {
        boolean result=false;
        if(sn==null || sn.equals("null") || sn==""){
            result=service.queryByName(cateName,null);
        }else{
            result=service.queryByName(cateName,sn );
        }
        return success("ok", result);
    }
}